import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import axios from "axios";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeIndex.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginIndex.vue"),
    meta: { redirectAlreadyLogin: true },
  },
  {
    path: "/signup",
    name: "",
    component: () => import("../views/SignUp.vue"),
    meta: { redirectAlreadyLogin: true },
  },
  {
    path: "/column/:id",
    name: "column",
    component: () => import("../views/ColumnDetail.vue"),
    meta: { requiredLogin: true }
  },
  {
    path: "/create",
    name: "create",
    component: () => import("../views/CreatePost.vue"),
    meta: { requiredLogin: true },
  },
  {
    path: "/post/:id",
    name: "post",
    component: () => import("../views/PostDetail.vue"),
    meta: { requiredLogin: true },
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
//路由守卫
// to:要进入的一个目标
// from:当前导航正要离开的路由
// next():如果有 next() 方法跳转 指向下一个路由
// router.beforeEach((to,from,next)=>{
//   if(to.name !== 'login' && !store.state.user.isLogin){
//     next({name:'login'})
//   }else{
//     next()
//   }
// })

// 通过路由元信息实现跳转
// router.beforeEach((to, from, next) => {
//   if(to.meta.requiredLogin && !store.state.user.isLogin) {
//     next({ name:'login' })
//   }else if(to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
//     next('/')
//   }else {
//     next()
//   }
// });
router.beforeEach((to, from, next) => {
  const { user, token } = store.state;
  const { redirectAlreadyLogin, requiredLogin } = to.meta;
  if (!user.isLogin) {
    // 没有登录
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      store
        .dispatch("fetchCurrentUser")
        .then(() => {
          if (redirectAlreadyLogin) {
            next("/");
          } else {
            next();
          }
        })
        .catch((e) => {
          console.log(e);
          store.commit('logout')
          next("/login");
        });
    } else {
      if (requiredLogin) {
        next("/login");
      } else {
        next();
      }
    }
  } else {
    // 登录
    if (redirectAlreadyLogin) {
      next("/");
    } else {
      next();
    }
  }
});

export default router;
